package com.langll.ai.minio.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.langll.ai.minio.model.UploadFileDTO;
import io.minio.*;
import io.minio.http.Method;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class MinioService {

    private final MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    // 初始化存储桶
    @PostConstruct
    public void init() throws Exception {
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(bucketName)
                .build());
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        }
    }

    @SneakyThrows
    public UploadFileDTO uploadFile(MultipartFile file) throws Exception {
        UploadFileDTO uploadFileDTO = new UploadFileDTO();
        //校验是否为图片
//        if (file.isEmpty()) {
//            throw new IllegalArgumentException("文件不能为空");
//        }
//        BufferedImage read = ImageIO.read(file.getInputStream());
//        if (read == null) {
//            throw new GuiguException(400,"文件不是图片");
//        }
        //判断桶是否存在不存在创建
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(bucketName)
                .build());
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        }
        /**随机生成文件名称
         * 1.生成文件夹名称(年-月-日表示)
         * 2.生成文件名称(uuid)
         * 3.文件后缀名保持不变
         */
        String directoryName = "/"+ DateUtil.today()+"/";
        //获取后缀名
        String extName = FileUtil.extName(file.getOriginalFilename());
        //使用uuid生成随机文件名
        String fileName = IdUtil.randomUUID();
        fileName = directoryName+fileName+"."+extName;

        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build());

        uploadFileDTO.setFileObjectName(fileName);
        uploadFileDTO.setFileObjectUrl(getPresignedObjectUrl(fileName));
        return uploadFileDTO;
    }

    /**
     * 获取1小时的 预签名URL
     * @param objectName
     * @return
     * @throws Exception
     */
    public String getPresignedObjectUrl(String objectName) throws Exception {
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .method(Method.GET)
                .expiry(1, TimeUnit.HOURS) //1小时过期
                .build());
    }
    // 下载文件
    public byte[] downloadFile(String objectName) throws Exception {
        return IOUtils.toByteArray(downloadFileInputStream(objectName));
    }

    // 下载文件
    public InputStream downloadFileInputStream(String objectName) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build());
    }

    // 删除文件
    public void deleteFile(String objectName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build());
    }
}